package com.lxp.queue;


import java.util.Arrays;

/**
 * 顺序队列实现
 *
 * @Author swd
 * @Create 2020/8/7 0007 16:17
 */
public class OrderQueue<T> {

    private T[] datas; //数组模拟队列
    private int maxSize; //队列元素个数
    private int front; //队列中第一个对象位置
    private int rear; //队列中当前对象位置

    public OrderQueue(int maxSize) {
        if (maxSize < 1) {
            maxSize = 1;
        }
        this.maxSize = maxSize;
        this.datas = (T[]) new Object[this.maxSize];//初始化数组必须放到上一行之后
        this.front = 0;
        this.rear = 0;
    }

    //队列的状态 队空 & 队满
    public boolean isNull() {
        if (this.front == this.rear)
            return true;
        else
            return false;
    }

    public boolean isFull() {
        if ((rear + 1) % this.maxSize == front)
            return true;
        else
            return false;
    }

    //添加
    public boolean offer(T data) {
        if (isFull()) {
            return false;//队满
        } else {
            this.datas[this.rear] = data;
            this.rear = (this.rear + 1) % this.maxSize; //队尾指针 +1
            return true;
        }
    }

    //删除
    public T poll() {
        if (isNull()) {
            return null;//队空
        } else {
            T pollData = this.datas[front];
            this.front = (this.front + 1) % this.maxSize; //队头指针 +1
            return pollData;
        }
    }

    //get/set

    public T[] getDatas() {
        return datas;
    }

    public void setDatas(T[] datas) {
        this.datas = datas;
    }

    public int getMaxSize() {
        return maxSize;
    }

    public void setMaxSize(int maxSize) {
        this.maxSize = maxSize;
    }

    public int getFront() {
        return front;
    }

    public void setFront(int front) {
        this.front = front;
    }

    public int getRear() {
        return rear;
    }

    public void setRear(int rear) {
        this.rear = rear;
    }

    @Override
    public String toString() {
        return "OrderQueue{" +
                "datas=" + Arrays.toString(datas) +
                ", maxSize=" + maxSize +
                ", front=" + front +
                ", rear=" + rear +
                '}';
    }
}
